//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package metric_serv

import (
	"context"
	"time"

	"google.golang.org/grpc"
)

func UnaryServerInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
		t1 := time.Now().UnixNano() / 1e6
		resp, err := handler(ctx, req)
		t2 := time.Now().UnixNano() / 1e6
		timeDiff := float64(t2 - t1)
		if err != nil {
			grpcCount.WithLabelValues(info.FullMethod, "error").Inc()
			grpcTime.WithLabelValues(info.FullMethod, "error").Observe(timeDiff)
		} else {
			grpcCount.WithLabelValues(info.FullMethod, "success").Inc()
			grpcTime.WithLabelValues(info.FullMethod, "success").Observe(timeDiff)
		}
		return resp, err
	}
}

func StreamServerInterceptor() grpc.StreamServerInterceptor {
	return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
		t1 := time.Now().UnixNano() / 1e6
		err = handler(srv, stream)
		t2 := time.Now().UnixNano() / 1e6
		timeDiff := float64(t2 - t1)
		if err != nil {
			grpcCount.WithLabelValues(info.FullMethod, "error").Inc()
			grpcTime.WithLabelValues(info.FullMethod, "error").Observe(timeDiff)
		} else {
			grpcCount.WithLabelValues(info.FullMethod, "success").Inc()
			grpcTime.WithLabelValues(info.FullMethod, "success").Observe(timeDiff)
		}
		return err
	}
}
